import { defineComponent } from "vue";
import style from "./index.module.less";
import { Col, Row } from "vant";
import { useUploader } from "@/hooks/uploader";
import close from "./asset/close.png";
import { formUploadProps } from "./types";
import * as vant from "vant";
const { showImagePreview, showFailToast } = vant;

export default defineComponent({
  name: "upload",
  props: formUploadProps,
  emits: ["change"],
  setup(props, { emit }) {
    const { upload } = useUploader({});
    return () => {
      const onPreview = (index: number) => {
        showImagePreview({
          images: getData(),
          startPosition: index,
        });
      };
      const onClose = (e: Event, index: number) => {
        e.stopPropagation();
        e.preventDefault();
        const data = getData();
        data.splice(index, 1);
        emit("change", data.toString());
      };
      const renderListItem = (url: any, index: number) => {
        return (
          <Col class="mt-[10px]">
            <div class={style.listItem} onClick={() => onPreview(index)}>
              <img src={url} />
              <img
                class="absolute right-0 top-0 w-[20px] h-[20px]"
                src={close}
                onClick={(e) => onClose(e, index)}
              />
            </div>
          </Col>
        );
      };
      const getData = () => {
        return props.modelValue.split(",").filter((e) => e);
      };
      const renderList = () => {
        return getData().map((e, i) => renderListItem(e, i));
      };
      function renderButton() {
        return (
          <Col class="mt-[10px]">
            <div
              class={style.uploadMain}
              onClick={() => {
                const urls = getData();
                if (
                  props.item.maxLength &&
                  urls.length >= props.item.maxLength
                ) {
                  showFailToast("超出上传限制数量");
                  return;
                }
                upload((url) => {
                  urls.push(url);
                  emit("change", urls.toString());
                });
              }}
            ></div>
          </Col>
        );
      }
      // 上传接口还没有对接过 所以这边先写个样子
      return (
        <Row gutter={5} class={"mb-[10px]"}>
          {renderList()}
          {renderButton()}
        </Row>
      );
    };
  },
});
